const { Service } = require('egg')
const cheerio = require('cheerio')
// const { tableToList } = require('../utils/tools');

module.exports = class CreditService extends Service {
  /**
   * * 学分修读情况
   * @return {Array} *
   */

  async table(sid) {
    const Cookie = this.ctx.state.Cookie
    const apiUrl1 = `${this.ctx.state.baseUrl}/jwglxt/xsxxxggl/xsgrxxwh_cxXsgrxx.html?gnmkdm=N100801&layout=default`
    const apiUrl2 = `${this.ctx.state.baseUrl}/jwglxt/xtgl/comm_cxZydmList.html`
    const apiUrl3 = `${this.ctx.state.baseUrl}/jwglxt/xjyj/xjyj_cxXjyjjdlb.html?gnmkdm=N105505`
    const apiUrl4 = `${this.ctx.state.baseUrl}/jwglxt/cjcx/cjcx_cxXsgrcj.html?doType=query&gnmkdm=N305005`
    const nj = `20${sid.substring(0, 2)}`
    let zy = 0
    let jgId = 0
    let zyhId = 0
    const detail = []// 存放json格式的信息
    const type = []// 存放课程种类
    const need = []// 存放所需学分
    const has = []// 存放已修学分

    // 第一次请求，请求学籍信息获取,以获得专业和专业id
    const res1 = await this.ctx.curl(apiUrl1, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    if (res1.status === 200) {
      try {
        const pageXml1 = res1.data.toString()
        const $ = cheerio.load(pageXml1)
        zy = $('#col_zyh_id').text().replace(/\s/g, '')
      } catch (err) {
        return err
      }
    }

    // 第二次请求,根据专业获取专业号id以及jg_id
    const res2 = await this.ctx.curl(apiUrl2, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    if (res2.status === 200) {
      try {
        const pageXml2 = res2.data.toString()
        const data2 = JSON.parse(pageXml2)
        const foundItem = data2.find((item) => item.zymc === zy)

        if (foundItem) {
          jgId = foundItem.jg_id
          zyhId = foundItem.zyh_id
        } else {
          console.log('没有找到匹配的学院')
        }
      } catch (err) {
        return err
      }
    }

    // 第三次请求，请求学分修读情况
    const res3 = await this.ctx.curl(apiUrl3, {
      method: 'POST',
      data: {
        jg_id: jgId,
        njdm_id: nj,
        zyh_id: zyhId,
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        Host: 'jw.hieu.edu.cn',
        Origin: 'http://jw.hieu.edu.cn',
      },
      timeout: 10000,
    })

    if (res3.status === 200) {
      try {
        const pageXml3 = res3.data.toString()
        const data = JSON.parse(pageXml3) // 将字符串解析为 JavaScript 对象
        for (const i of data) {
          type.push(i.xfyqjdmc) // 获取课程种类
          need.push(i.yqzdxf) // 获取所需学分
        }
      } catch (err) {
        return err
      }
    }

    // 第四次请求,请求成绩，跟成绩进行比对，得到修读情况
    const res4 = await this.ctx.curl(apiUrl4, {
      method: 'POST',
      data: {
        xnm: '',
        xqm: '',
        kcbj: '',
        _search: false,
        nd: 1705072135642,
        'queryModel.showCount': 300,
        'queryModel.currentPage': 1,
        'queryModel.sortName': '',
        'queryModel.sortOrder': 'asc',
        time: 2,
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        Host: 'jw.hieu.edu.cn',
        Origin: 'http://jw.hieu.edu.cn',
      },
      timeout: 1000,
    })
    if (res4.status === 200) {
      try {
        const tableList = JSON.parse(res4.data.toString())
        const data1 = tableList.items
        if (data1 === undefined || data1.length === 0) { // 判断是否有数据
          return {}
        }
        for (let i = 0; i < type.length; i++) {
          detail.push([])
        }
        const data = data1.map((item) => ({ // 更改键值
          N: item.kcmc,
          T: `${item.xnmmc}-${item.xqmmc}`,
          C: item.xf,
          G: item.cj,
          S: '',
          kcxzmc: item.kcxzmc,
        }))
        const detailMap = {} // 使用一个对象来映射 kcxzmc 到 detail 的索引
        for (const item of data) {
          const kcxzmc = item.kcxzmc
          if (detailMap[kcxzmc]) {
            detail[detailMap[kcxzmc]].push(item)
          } else {
            const typeIndex = type.indexOf(kcxzmc)
            if (typeIndex !== -1) { // 如果在，更新 detailMap 并添加 item 到对应的 detail 子数组
              detailMap[kcxzmc] = typeIndex
              detail[typeIndex].push(item)
            } else { // 如果不在，将 kcxzmc 添加到 type 数组和 detail 数组，并更新 detailMap
              const newIndex = type.push(kcxzmc) - 1 // 得到索引
              detail.push([]) // 在 detail 数组中添加新的空子数组
              detailMap[kcxzmc] = newIndex
              detail[newIndex].push(item) // 将 item 添加到新的 detail 子数组
            }
          }
          // 根据 i.G 的值设置 i.S 的值
          item.S = item.G === '0' || item.G === '不及格' ? '未获' : '已获'
        }
        for (const i of detail) {
          for (let j = 0; j < i.length; j++) {
            for (const k in i[j]) {
              if (k === 'kcxzmc') {
                delete i[j][k]
              }
            }
          }
        }
        for (const i of detail) {
          let v = 0
          for (let j = 0; j < i.length; j++) {
            if (i[j].S === '已获') { // 计算已获学分
              const x = parseFloat(i[j].C)
              v += x
            }
          }
          has.push(v)
        }
        const table = []
        for (let i = 0; i < type.length; i++) {
          const dataJson = { // 构建json对象
            category: type[i],
            details: detail[i],
            need: need[i] || '0',
            has: (Math.round(has[i] * 100) / 100).toString(), // 保留两位小数
          }
          table.push(dataJson)
        }

        return table
      } catch (err) {
        return err
      }
    }

    return {}
  }

  /**
   * * 创新学分、素拓分、第二课堂分
   * @return {Array} *
   */
  async extra() {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/jwglxt/xmfzgl/xshdfzcx_cxXmfzqr.html?gnmkdm=N4780`
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      data: {
        xmlbmc: '创新创业学分',
        _search: 'false',
        nd: '1705892475328',
        queryModel: ['15', '1', '', 'asc'],
        time: '0',
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    const info = {}
    if (res.status === 200) {
      try {
        const pageXml1 = res.data.toString()
        const pageObj1 = JSON.parse(pageXml1) // 将字符串解析为 JavaScript 对象
        return pageObj1
      } catch (err) {
        return err
      }
    }
    return info
  }
}
